<?php

class Setting extends Controller {

	public function run() {
		if (empty($_GET['plugin']) || empty($_GET['ver'])) {
			$this->template('message', array('message' => '参数错误'));
		}

		$plugin = $_GET['plugin'];
		$ver = $_GET['ver'];
		$page = !empty($_GET['page']) ? $_GET['page'] : '';

		$info = Sdk\lib\Core::GetInfo(array($plugin => array($ver)));

		$settingConf = array();
		$f = ROOT_PATH . '/www/' . $plugin . '/' . $ver . '/conf/setting.yaml';
		if (file_exists($f)) {
			$data = file_get_contents($f);

			$settingConf = \Sdk\lib\Core::ParseSetting($data);
			if (!$page) {
				$page = array_keys($settingConf)[0];
			}

			if (isset($settingConf[$page]['controller'])) {
				$controller = $settingConf[$page]['controller'];
				$action = $settingConf[$page]['controller']['action'] ?? 'index';
				header('location: ' . Common::getURI('/plugin/' . $plugin . '/' . $ver . '/' . $controller . '/' . $action));
				exit;
			}
		}
		$settingValue = array();
		$f = ROOT_PATH . '/www/' . $plugin . '/' . $ver . '/conf/setting.php';
		if (file_exists($f)) {
			require_once $f;
		}

		if (!empty($_POST)) {
			$s = $_POST['s'];
			foreach ($s as $key => $value) {
				if (isset($settingConf[$page]['items'][$key])) {
					$settingValue[$key] = $value;
				}
			}
			file_put_contents($f, "<?php\n \$settingValue = " . var_export($settingValue, true) . ';');
		}

		$this->template('setting', array(
			'appName' => !empty($info[$plugin]) ? $info[$plugin]['name'] : '',
			'branchName' => !empty($info[$plugin]['branch'][$ver]) ? $info[$plugin]['branch'][$ver] : '',
			'plugin' => $plugin,
			'ver' => $ver,
			'page' => $page,
			'settingConf' => $settingConf,
			'settingValue' => $settingValue,
		));
	}

}